import os
from typing import List, Any

from aop.aop_timeit import timeit
from models.models_prod import OpOuterGoods as ProdOpOuterGoodsModel
from services.dev.dev_outer_goods_service import DevOuterGoodsService
from services.prod.prod_service import ProdService
from sync import delete_tag, sync_tag
from sync.base_sync import BaseSync
from utils.date_tuils import get_yesterday_time_range
from utils.log_utils import get_logger

# 获取一个命名的日志记录器
logger = get_logger(__name__,os.path.splitext(os.path.basename(__file__))[0])

class SyncOuterGoods(BaseSync):
    def insert_dev_data(self, items: List[Any], session=None):
        self.dev_service.add(items, session=session)

    def __init__(self, prod_model_class: ProdService, dev_service:DevOuterGoodsService, time_field='create_time'):
        super().__init__(prod_service=prod_model_class, dev_service=dev_service)
        self.time_field = time_field
        self.dev_service = dev_service

@timeit(name="SyncOuterGoods")
def main(s=None, e=None):
    """

    :param s: 开始时间
    :param e: 结束时间
    """
    try:
        if s and e:
            start, end = s, e
        else:
            start, end = get_yesterday_time_range()
        prod_service = ProdService(model_class=ProdOpOuterGoodsModel, time_field='create_time')
        dev_service = DevOuterGoodsService()
        with SyncOuterGoods(prod_service, dev_service, time_field='create_time') as syncer:
            syncer.show_total_count(start, end)
            if delete_tag():
                logger.info("删除指定区间的数据")
                syncer.delete_dev_data(start, end)

            if sync_tag():
                logger.info("同步指定区间数据")
                syncer.sync_page(start, end)

    except Exception as e:
        logger.error("主程序异常退出: %s", e, exc_info=True)


if __name__ == '__main__':
    main()
